package com.mlethe.android.demo.seattable.activity;

import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.mlethe.android.demo.R;
import com.mlethe.android.demo.seattable.adapter.SeatAdapter;
import com.mlethe.android.demo.seattable.base.BaseActivity;
import com.mlethe.android.demo.seattable.entity.CineSeat;
import com.mlethe.android.demo.seattable.entity.Hall;
import com.mlethe.android.demo.seattable.entity.Obj;
import com.mlethe.android.demo.seattable.entity.Result;
import com.mlethe.android.demo.seattable.presenter.SeatTablePresenter;
import com.mlethe.library.navigation.DefaultNavigationBar;
import com.mlethe.library.recyclerview.listener.OnItemClickListener;
import com.mlethe.library.recyclerview.decoration.LinearItemDecoration;
import com.mlethe.library.utils.file.FileUtil;
import com.mlethe.library.widget.seattable.Seat;
import com.mlethe.library.widget.seattable.SeatTableView;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class SeatTableActivity extends BaseActivity<SeatTablePresenter, com.mlethe.android.demo.seattable.view.SeatTableView> implements com.mlethe.android.demo.seattable.view.SeatTableView,View.OnClickListener {

    private TextView movieNameTv, movieInfoTv, movieConfirmTv;
    private SeatTableView seatTableView;
    private RecyclerView recyclerView;

    private SeatAdapter adapter;

    private double totalPrice = 0;

    private Hall hall;

    @Override
    protected SeatTablePresenter createPresenter() {
        return new SeatTablePresenter(this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_seat_table);
    }

    @Override
    protected void initTitle() {
        new DefaultNavigationBar.Builder(this)
                .setBackgroundResource(R.color.colorPrimary)
                .setTitle("重庆华熙国际影城")
                .create();
    }

    @Override
    protected void initView() {
        movieNameTv = findViewById(R.id.movie_name_tv);
        movieInfoTv = findViewById(R.id.movie_info_tv);
        seatTableView = findViewById(R.id.seat_table);
        recyclerView = findViewById(R.id.movie_ticket_rv);
        movieConfirmTv = findViewById(R.id.movie_confirm_tv);
        movieConfirmTv.setOnClickListener(this);

        adapter = new SeatAdapter();
        adapter.setOnItemClickListener(new OnItemClickListener<Seat>() {
            @Override
            public void onItemClick(@NotNull View view, Seat item, int position) {
                seatTableView.unselect(item);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new LinearItemDecoration(this).setDrawable(R.drawable.line_20dp).setSize(20).setAroundShow(false, true, false, true));
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        hall = getIntent().getParcelableExtra("hall");
        if (hall == null) {
//            finish();
//            return;
            hall = new Hall();
            hall.setMarketPrice(20);
            hall.setHallName("测试");
            String seatJson = FileUtil.getAssetsFile(this, "seat.json");
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            Result<Obj<List<CineSeat>>> result = gson.fromJson(seatJson, new TypeToken<Result<Obj<List<CineSeat>>>>(){}.getType());
            if (!result.isOk()) {
                Toast.makeText(this, result.getContent(), Toast.LENGTH_SHORT).show();
            } else if (!result.getObject().getRes().isOk()){
                Toast.makeText(this, result.getObject().getRes().getErrorMessage(), Toast.LENGTH_SHORT).show();
            } else {
                handleSeatsData(result.getObject().getRes().getData());
            }
            return;
        }
        movieNameTv.setText(hall.getMovieInfo().get(0).getMovieName());
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        movieInfoTv.setText(String.format(getString(R.string.movie_info), hall.getBusinessDate(), sdf.format(hall.getStartTime()), sdf.format(hall.getEndTime()), hall.getMovieInfo().get(0).getMovieLanguage()));
        adapter.setPrice(hall.getMarketPrice());
        mPresenter.cinemaPlaySeatStatus(hall.getId(), hall.getCineUpdateTime());
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.movie_confirm_tv) {
            Toast.makeText(this, "支付" + totalPrice + "元", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理座位图数据
     * @param cineSeats
     */
    private void handleSeatsData(List<CineSeat> cineSeats) {
        List<List<Seat>> seats = new ArrayList<>();
        List<Seat> list = new ArrayList<>();
        for (int i = 0; i < cineSeats.size(); i++) {
            CineSeat cineSeat = cineSeats.get(i);
            if (seats.size() == 0) {
                seats.add(list);
            } else {
                List<Seat> rows = seats.get(seats.size() - 1);
                Seat seat = rows.get(0);
                if (seat.getX() != cineSeat.getXCoord()) {
                    list = new ArrayList<>();
                    seats.add(list);
                }
            }
            int state = Seat.SEAT_TYPE_SOLD;
            if ("road".equals(cineSeat.getType())) {
                state = Seat.SEAT_TYPE_NOT_AVAILABLE;
            } else if ("ok".equals(cineSeat.getStatus())) {
                state = Seat.SEAT_TYPE_AVAILABLE;
            }
            int type = Seat.ROAD;
            if ("danren".equals(cineSeat.getType())) {
                type = Seat.SINGLE_PERSON_SEAT;
            } else if ("shuangren".equals(cineSeat.getType())) {
                type = Seat.DOUBLE_MAN_SEAT;
                list.add(new Seat(cineSeat.getCineSeatId(), cineSeat.getXCoord(), cineSeat.getYCoord(),cineSeat.getRow(), cineSeat.getColumn(), type, state, cineSeat.getPairValue()));
                continue;
            } else if ("baoliu".equals(cineSeat.getType())) {
                type = Seat.RETAIN_SEAT;
            } else if ("canji".equals(cineSeat.getType())) {
                type = Seat.DEFORMITY_SEAT;
            } else if ("vip".equals(cineSeat.getType())) {
                type = Seat.VIP_SEAT;
            } else if ("zhendong".equals(cineSeat.getType())) {
                type = Seat.VIBRATE_SEAT;
            }
            list.add(new Seat(cineSeat.getCineSeatId(), cineSeat.getXCoord(), cineSeat.getYCoord(),cineSeat.getRow(), cineSeat.getColumn(), type, state));
        }
        notifySeatTable(seats);
    }

    @Override
    public void notifySeatTable(List<List<Seat>> seats) {
        seatTableView.setScreenText(hall.getHallName())
                .setCheckListener(new SeatTableView.CheckListener() {
                    @Override
                    public void checked(Seat seat) {
                        Log.e("TAG", "checked: " + seat.getRow() + "排" + seat.getColumn() + "座");
                        int size = adapter.getDataSize();
                        if (size <= 0) {
                            recyclerView.setVisibility(View.VISIBLE);
                            movieConfirmTv.setVisibility(View.VISIBLE);
                        }
                        adapter.notifyItemInsert(seat);
                        totalPrice += hall.getMarketPrice();
                        movieConfirmTv.setText(String.format(getString(R.string.confirm_choose), totalPrice));
                    }

                    @Override
                    public void uncheck(Seat seat) {
                        Log.e("TAG", "uncheck: " + seat.getRow() + "排" + seat.getColumn() + "座");
                        adapter.notifyItemRemove(seat);
                        adapter.notifyDataSetChanged();
                        totalPrice -= hall.getMarketPrice();
                        movieConfirmTv.setText(String.format(getString(R.string.confirm_choose), totalPrice));
                        if (adapter.getDataSize() <= 0) {
                            recyclerView.setVisibility(View.GONE);
                            movieConfirmTv.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void overstep(int max) {
                        Toast.makeText(SeatTableActivity.this, "最多只能选择" + max + "个", Toast.LENGTH_SHORT).show();
                    }
                })
                .setSeat(seats);
    }
}
